﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace BusinessIntelligenceToolkit.Controls.ContainerGenerators
{
    public class BitItemsControlContainerGenerator : DependencyObject, IContainerGenerator
    {
        protected readonly BitItemsControl Target;

        public BitItemsControlContainerGenerator(BitItemsControl target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");    
            }

            Target = target;
        }

        public virtual UIElement CreateContainer()
        {
            var container = new ContentPresenter();
            return container;
        }

        public virtual UIElement PrepareContainerForItem(UIElement container, object data)
        {
            ContentPresenter contentPresenter = container as ContentPresenter;
            contentPresenter.Content = data;
            contentPresenter.ContentTemplate = Target.ItemTemplate;

            Binding binding = new Binding()
                                  {
                                      Source = Target,
                                      Path = new PropertyPath("HorizontalContentAlignment")
                                  };

            contentPresenter.SetBinding(Control.HorizontalAlignmentProperty, binding);
            return contentPresenter;
        }

        public virtual void ClearContainer(UIElement container)
        {
            ContentPresenter contentPresenter = container as ContentPresenter;
            contentPresenter.Content = null;
            contentPresenter.ContentTemplate = null;
        }

        public virtual bool ContainerContainsEqualData(UIElement container, object data)
        {
            ContentPresenter contentPresenter = container as ContentPresenter;
            if (contentPresenter.Content == null)
            {
                return false;
            }

            bool areEquals = contentPresenter.Content.Equals(data);
            return areEquals;
        }

        public virtual bool IsContainerClear(UIElement container)
        {
            ContentPresenter contentPresenter = container as ContentPresenter;
            return contentPresenter.ContentTemplate == null;
        }
    }
}